from twitter import TwittApi
from delicious import DelicApi
from multipart import TwitPicApi
import urllib
import subprocess
import pickle
import os

from Tkinter import *
import tkSimpleDialog
import time

#from ningcook import NingApi
import thread

class Gui:
	def __init__(self, master):
		self.account_file = os.path.expanduser("~") + "/" + ".account.del"
		
		self.initComponent(master)
		self.master = master
		self.createApiObject()


		# append ning
		#self.ning = NingApi("wearetherock@hotmail.com", "")

		

	def createApiObject(self):
		if not os.path.exists(self.account_file) :
			self.showSettingDialog()

		f = open(self.account_file,"rb")
		upk = pickle.Unpickler(f)
		account = upk.load()
		f.close()

		twitt_user = account["TWITT_USER"]
		twitt_pass = account["TWITT_PASS"]
		delic_user = account["DELIC_USER"]
		delic_pass = account["DELIC_PASS"]

		print twitt_user, twitt_pass, delic_user, delic_pass
		
		self.twitt = TwittApi(twitt_user, twitt_pass)
		self.delic = DelicApi(delic_user, delic_pass)
		self.twit_pic = TwitPicApi(twitt_user, twitt_pass)

	def initComponent(self,master):
		frame = Frame(master, width=800, height=400, bd=1)
		frame.pack()

		#url
		url_frame = Frame(frame)
		url_label = Label(url_frame, text="URL :")
		url_label.pack(side=LEFT, padx=5)
		
		self.url_var = StringVar()
		url_entry = Entry(url_frame, textvariable=self.url_var, bg="white", width=50)
		url_entry.pack(side=RIGHT, padx=5)
		url_frame.pack(expand=1, fill=X, pady=0, padx=0)

		#title
		title_frame = Frame(frame)
		title_label = Label(title_frame, text="Title :")
		title_label.pack(side=LEFT, padx=5)
		
		self.title_var = StringVar()
		title_entry = Entry(title_frame, textvariable=self.title_var, bg="white", width=50)
		title_entry.pack(side=RIGHT, padx=5)
		title_frame.pack(expand=1, fill=X, pady=0, padx=0)

		#tag
		tag_frame = Frame(frame)
		tag_label = Label(tag_frame, text="Tags :")
		tag_label.pack(side=LEFT, padx=5)
		
		self.tag_var = StringVar()
		tag_entry = Entry(tag_frame, textvariable=self.tag_var, bg="white", width=50)
		tag_entry.pack(side=RIGHT, padx=5)
		tag_frame.pack(expand=1, fill=X, pady=0, padx=0)

		
		#check box
		update_frame = Frame(frame)
		update_frame.pack(side=RIGHT)

		setting_button  = Button(update_frame, text="Setting", command=self.showSettingDialog)
		setting_button.pack(side=LEFT)

		self.cap_var = IntVar()
		cap_var = Checkbutton(update_frame, text="Capture?", variable=self.cap_var)
		cap_var.pack(side=LEFT)

		self.tweet_var = IntVar()
		tweet_check = Checkbutton(update_frame, text="Tweet?", variable=self.tweet_var) 
		tweet_check.pack(side=LEFT)

		self.mark_var = IntVar()
		mark_check = Checkbutton(update_frame, text="Mark?", variable=self.mark_var)
		mark_check.pack(side=LEFT)

		update_button = Button(update_frame, text="Update", command=self.updateStatus)
		update_button.pack(side=RIGHT)


	def showSettingDialog(self):
		s = SettingDialog(self.master)
		account = {}
		account["TWITT_USER"] = s.twitt_user
		account["TWITT_PASS"] = s.twitt_pass
		account["DELIC_USER"] = s.delic_user
		account["DELIC_PASS"] = s.delic_pass

		f = open(self.account_file, "wb")
		pk = pickle.Pickler(f)
		pk.dump(account)
		f.close()

		self.twitt = TwittApi(s.twitt_user, s.twitt_pass)
		self.delic = DelicApi(s.delic_user, s.delic_pass)	

	def postNing(self, message):
		#self.ning.post(message)
		os.system("""python ningcook.py "%s" "%s" "%s" """ % 
			("wearetherock@hotmail.com", "", message))

	def updateStatus(self):
		print "updating ..."
		url = self.url_var.get()
		title = self.title_var.get()
		tags = self.tag_var.get()
		tweet = self.tweet_var.get()
		mark = self.mark_var.get()
		cap = self.cap_var.get()
		
		if mark :
			self.delic.addNewBookmark(url, urllib.quote_plus(title),tags)

		if cap:
			os.system("import snapshot/wearetherock.png")
			time.sleep(.2)

			"""
			convert -font fonts/1900805.ttf -fill white -pointsize 36 \
			-draw 'text 10,475 "stillhq.com"' \
			floriade.jpg stillhq.jpg
			"""
			os.system("""convert -font BeatMyGuest.ttf -fill white -pointsize 30 -draw 'text 20,20 " wearetherock@gmail.com "' -draw 'image over 5,4 20,20 "blackhat.png"' snapshot/wearetherock.png snapshot/wearetherock2.png""")
			time.sleep(.2)
			self.twit_pic.post(title.encode("utf-8"), "snapshot/wearetherock2.png")

		elif tweet :
			message = " "+self.makeTinyUrl(url)
			print message
			self.twitt.squawk(title.encode('utf-8') + message)

			# post ning
			# thread.start_new_thread(self.postNing,(title.encode('utf-8') + message,))

		self.url_var.set("")
		self.title_var.set("")
		self.tag_var.set("")

	def makeTinyUrl(self,url):
		if url == "":
			proc = subprocess.Popen("fortune -s", stdout=subprocess.PIPE, shell=True)
			proc.wait()
			result = proc.stdout.readlines()
			#return "~"+ " ".join(result)
			return "."

		apiurl = "http://tinyurl.com/api-create.php?url="
		tinyurl = urllib.urlopen(apiurl + urllib.quote_plus(url)).read()
		return tinyurl.strip()
	
class SettingDialog(tkSimpleDialog.Dialog):
	def body(self, master):

		self.account_file = os.path.expanduser("~") + "/" + ".account.del"
		#twitter
		Label(master, text = "Twitter Username :").grid(row=0, sticky=E)
		Label(master, text = "Twitter Password :").grid(row=1, sticky=E)

		self.twitt_user_entry = Entry(master)
		self.twitt_pass_entry = Entry(master)
		self.twitt_user_entry.grid(row=0, column=1)
		self.twitt_pass_entry.grid(row=1, column=1)
		
		#delicious
		Label(master, text = "Delicious Username :").grid(row=2, sticky=E)
		Label(master, text = "Delicious Password :").grid(row=3, sticky=E)

		self.delic_user_entry = Entry(master)
		self.delic_pass_entry = Entry(master)
		self.delic_user_entry.grid(row=2,column=1)
		self.delic_pass_entry.grid(row=3,column=1)

		if os.path.exists(self.account_file) :
			f = open(self.account_file,"rb")
			upk = pickle.Unpickler(f)
			account = upk.load()
			f.close()

			self.twitt_user_entry.insert(0,account["TWITT_USER"])
			self.twitt_pass_entry.insert(0,account["TWITT_PASS"])
			self.delic_user_entry.insert(0,account["DELIC_USER"])
			self.delic_pass_entry.insert(0,account["DELIC_PASS"])
	

	def apply(self):
		self.twitt_user = self.twitt_user_entry.get()
		self.twitt_pass = self.twitt_pass_entry.get()
		self.delic_user = self.delic_user_entry.get()
		self.delic_pass = self.delic_pass_entry.get()


root = Tk()
root.title("tiny-delicious client")
g = Gui(root)
root.mainloop()
